<template>
  <div>
    <div class="px-6 py-4">
      <div class="m-4">
        <select
          class="badge"
          v-model="selectId"
          @change="changeSelectType"
          clearable
        >
          <option :value="i.id" v-for="i in categorieData" :key="i.id">
            {{ i.name }}
          </option>
        </select>
        <button
          type="button"
          class="bg-red-500 text-white font-semibold rounded-lg shadow-md px-2"
          @click="resetData"
        >
          重置类别
        </button>
      </div>
      <ul>
        <li
          class="
            m-4
            bg-purple-300
            text-white
            font-semibold
            rounded-lg
            shadow-md
          "
          v-for="item in goodsList"
          :key="item.uuid"
        >
          {{ item.name }}}
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
  export default {
    name: "IndexPage",
    data() {
      return {
        // 商品列表
        goodsList: [],
        // 商品类别
        categorieData: [],
        // 选择的类别
        selectId: "",
      }
    },
    methods: {
      // 获取商品类别
      getCategorieData() {
        this.$axios
          .get("/api/categories" + "")
          .then((res) => {
            if (res.status === 200) this.categorieData = res?.data?.data
          })
          .catch((err) => {
            console.log(err)
          })
      },
      // 获取商品列表
      getProduct(params = "") {
        this.$axios
          .get("api/products?category=" + params)
          .then((res) => {
            if (res.status === 200) this.goodsList = res?.data?.data
          })
          .catch((err) => {
            console.log(err)
          })
      },
      // 监听选择的类别
      changeSelectType() {
        this.getProduct(this.selectId)
      },
      // 重置数据
      resetData() {
        this.getProduct("")
      },
    },

    created() {
      this.getCategorieData()
      this.getProduct()
    },
  }
</script>
<style lang="postcss" scoped>
  .badge {
    @apply inline-block bg-gray-200 rounded-full px-3 py-1 text-sm font-semibold text-gray-700;
    &:hover {
      @apply bg-gray-300;
    }
  }
</style>
